import actors.Actor
import actors.Actor._
import actors.remote.RemoteActor._
import java.io.{FileInputStream, ObjectInputStream}

/**
 * Created by Yair, using IntelliJ IDEA.
 * Date: 16/06/11
 * Time: 15:46
 */

object controllerListener extends Actor{

  var controllerPort: Int = 8926

  def act(){
    //register the actor - the server
    alive(controllerPort)
    register('controller, self)

    while (true){
      receive{

        case "STOP" => {
          //stop the Manager, OS listener
          Manager.stopManager
        }

        case "START" =>{
          //start the Manager, OS listener
          Manager.startManager
        }

          //if got request to update the account's details
          case "NEW ACCOUNT" =>{
            //load the account configuration file
            val in_c: ObjectInputStream  = new ObjectInputStream(new FileInputStream("c:\\CDB\\cdb.account.configuration")) //remove c:\cdb
            val account_config: AccountConfig =in_c.readObject.asInstanceOf[AccountConfig]
            in_c.close

            //set the current account with te given details
            Manager.setAccount(account_config.cdb_Path, account_config.userName, account_config.password)
          }


        case "NEW USER" =>{
          //try to create new user

          //load the account configuration file
          val in_c: ObjectInputStream  = new ObjectInputStream(new FileInputStream("c:\\CDB\\cdb.account.configuration")) //remove c:\cdb
          val account_config: AccountConfig =in_c.readObject.asInstanceOf[AccountConfig]
          in_c.close

          //set the current account as a temp account details
          Manager.setAccount(account_config.cdb_Path, account_config.userName, account_config.password)

          //send the request to the server
          val valid = Manager.createUsr

          //return the answer to the sender of this message
          sender ! valid
        }


      }
    }
  }
}



/*

if (str.startsWith("Account, ")){
              var inp = str.substring(8)  //8  or 9??

              //extract the details of the account
              if (inp.startsWith("userName:")){
                inp = inp.substring(8) // or 9 ??

                var i = inp.indexOf(" ")
                val userName = inp.substring(0, i)

                // make sure that i+1 < inp length
                inp = inp.substring(i+1)

                if (inp.startsWith("password: ")){
                  inp = inp.substring(9)  //9 or 10 ??

                  val password = inp

                  else if (str.startsWith("newUsr: ")){

                    }
                }
              }
            }
            */